<!-- 编辑弹窗 -->
<template>
    <ele-modal
      inner
      width="40%"
      :movable="true"
      :visible="visible"
      :close-on-click-modal="true"
      :before-close="handleClose"
      custom-class="ele-dialog-form"
      :title="isUpdate ? '修改清关费信息' : '添加清关费信息'"
      @update:visible="updateVisible" 
    >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
      <el-card  >      
        <el-row :gutter="24">
          <el-col :md="24" :sm="24">
            <el-form-item label="费用公司:" prop="supplierId">
              <el-select  style="width: 100%;" filterable clearable v-model="form.supplierId" placeholder="请选择费用公司"  @change="changeThreeCompany" >
                <el-option  v-for="item in QGCompanyDatas" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="24" :sm="24" >
            <el-form-item label="币种:"  prop="currencyId" >
              <el-select  filterable clearable v-model="form.currencyId" placeholder="请选择币种" class="ele-fluid" @change="changeCurrency">
                <el-option v-for="item in hbDatas" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="24" :sm="24" >
            <el-form-item label="金额:"  prop="amount"  >
              <el-form-item label-width="10" style="margin-bottom:0;" >
                  <el-input v-model="form.amount" placeholder="请输入金额"  @change="setExchangeAmount()"  @keyup.native="form.amount = form.amount.replace(/[^\d.]/g,'');
                  form.amount = form.amount.replace(/\.{2,}/g,'.');
                  form.amount = form.amount.replace(/^\./g,'');
                  form.amount = form.amount.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  form.amount = form.amount.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');"/>
                </el-form-item>
            </el-form-item>
          </el-col>
          <el-col :md="24" :sm="24" >
            <el-form-item label="汇率:"  prop="rate" >
              <el-form-item label-width="10" style="margin-bottom:0;"  >
                <el-input v-model="form.rate" placeholder="请输入汇率" :disabled="form.currencyCode=='C-HB01'" @change="setExchangeAmount()"    @keyup.native="form.rate = form.rate.replace(/[^\d.]/g,'');
                  form.rate = form.rate.replace(/\.{4,}/g,'.');
                  form.rate = form.rate.replace(/^\./g,'');
                  form.rate = form.rate.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  form.rate = form.rate.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');"/>
                </el-form-item>
            </el-form-item>
          </el-col>
          <el-col :md="24" :sm="24" >
            <el-form-item label="金额(￥):"  >
              <el-input v-model="form.amountCn" disabled />
            </el-form-item>
          </el-col>
          <el-col :md="24" :sm="24" >
            <el-form-item label="备注:"  >
              <el-input v-model="form.remarks" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card shadow="never"> </el-card>
    </el-form>
    <div slot="footer">
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save" >
        保存
      </el-button>
    </div>
    </ele-modal>
  </template>
  <script>
   import { getUser } from '@/utils/user-util';
   import { QueryModelByScurrencyId } from '@/api/basicdatamanager/ratemanager';
   import { QueryAllChildDictViewByCode } from '@/api/systemmanager/dictmanager';
   import { GetAllBSupplier, QuerySupplierByType} from '@/api/basicdatamanager/supplier';
   import { AddInordercost,GetModelByInorderId,UpdateInordercost} from '@/api/inventory/inordercost';

    export default {
      name: 'CostEdit',
      props: {
        // 弹窗是否打开
        visible: Boolean,
        // 修改回显的数据
        data: Object,
        // 入库id
        stockId:String,
      },
      data() {
        return {
          
          // 表单数据
          form: {amount:0,amountCn:0,inOrderId:'',supplierId:'',costId:'',costNumber:'',rate:0,currencyId:''},
          // 表单验证规则
          rules: {
            rate: [{required: true,message: '请输入汇率',trigger: 'blur'}],
            amount: [{required: true,message: '请输入金额',trigger: 'blur'}],
            supplierId: [{required: true,message: '请选择清关公司',trigger: 'blur'}],
            currencyId: [{required: true,message: '请选择币种',trigger: 'blur'}],
          },
         
          // 提交状态
          loading: false,
          // 是否是修改
          isUpdate: false,
          hbDatas:[],
          supplierDatas:[],
          QGCompanyDatas:[],
        };
      },

      created(){
        
        
      },
      methods: {

        /* 初始化数据 */
        initData(){

          //清关费
          QuerySupplierByType(3).then((res)=>{
            this.QGCompanyDatas = [];
            this.QGCompanyDatas = res;
          });

          QueryAllChildDictViewByCode(this.Constant.C_HB).then((res)=>{
            this.hbDatas = [];
            this.hbDatas = res;
          });

         

          GetAllBSupplier().then((res)=>{
            this.supplierDatas = [];
            this.supplierDatas = res;
          });
        },

        initCost(){
          QueryAllChildDictViewByCode(this.Constant.C_FYLX).then((res)=>{
            res.map((d)=>{
              if(d.code == "C-FYLX03"){
                this.form.costId = d.id;
                this.form.costNumber = d.code;
              }
            })
          });
        },

        save() {
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}

           if(this.data.inOrderId!=null && this.data.inOrderId!=undefined && this.data.inOrderId!='') {
              this.loading = true;
              const saveOrUpdate = this.isUpdate ? UpdateInordercost : AddInordercost;
              saveOrUpdate(this.form)
                .then((msg) => {
                  this.loading = false;
                  this.$message.success(msg);
                  this.updateVisible(false);
                  //回调父组件方法
                  this.$emit('callback');
                  this.$emit('update:visible', false);
                })
                .catch((e) => {
                  this.loading = false;
                  this.$message.error(e.message);
              });
           }
           else{
              //回调父组件方法
              this.$emit('callback',this.form);
              this.$emit('update:visible', false);
           }
            
          });
        },

        setData(id){
          GetModelByInorderId(id)
            .then((res) => {
              this.form = res; 
              if(!this.form) this.form = {amount:0,amountCn:0,inOrderId:this.data.inOrderId,supplierId:'',costId:'',costNumber:'',currencyId:''};
          });
        },

        changeCurrency(val){
          let hb = this.hbDatas.find((p)=>p.id === val)
          if(hb){
           this.form.currencyCode = hb.code;
           if(hb.code == 'C-HB01'){
              this.form.rate = 1;
              this.form.amountCn = this.form.amount;
           }else{
            QueryModelByScurrencyId(val).then((res)=>{
              this.form.rate = res.rate;
              this.form.amountCn = (this.form.amount * res.rate ).toFixed(4);
            })
           }
          }
        },

        //选择第三方公司
        changeThreeCompany(val){

          let qgCompany = this.QGCompanyDatas.find((p)=>p.id === val)
          if(qgCompany){
            this.form.rate = qgCompany.rate;
            this.form.currencyId = qgCompany.currencyId;
            this.form.supplierTypeId = qgCompany.typeId;
            this.changeCurrency(qgCompany.currencyId);
          }
        },


        setExchangeAmount(){
          if(this.form.amount && this.form.rate){
              let rate = parseFloat(this.form.rate);
              let amount = parseFloat(this.form.amount);

              if(this.form.costNumber =='C-FYLX03')this.form.clearAmount = amount;  //港杂费
              if(this.form.currencyCode == 'C-HB01'){
                this.form.rate =1;
                this.form.amountCn = amount;
              }else{
                this.form.amountCn = (amount*rate).toFixed(4);
              }
          }
        },
     
        /* 更新visible */
        updateVisible(value) {
          //更新父组件中的visible的值
          this.$emit('update:visible', value);
        },

        handleClose() {
          this.$emit('update:visible', false);
        },
    },
     
      /* 监听visible属性变化 */
      watch: {
        visible(visible) {
          this.initCost();
          this.initData();

          if (visible) {

            if (this.data && !this.data.isAdd) {
              //赋值this.form
              if(this.data.inOrderId){
                this.setData(this.data.inOrderId);
              }else{
                this.form = this.data;

              }
              
              this.isUpdate = true;
            } else {
              this.form={amount:0,amountCn:0,inOrderId:this.data?.inOrderId,supplierId:'',costId:'',costNumber:'',rate:0,currencyId:''};
              this.initCost();
              this.isUpdate = false;
            }
          } else {
              this.$refs['form'].clearValidate();
              this.form={amount:0,amountCn:0,inOrderId:this.data?.inOrderId,supplierId:'',costId:'',costNumber:'',rate:0,currencyId:''};
              this.initCost();
              let currentUser = getUser();
              this.form.operatorId = currentUser.accountId;
              this.form.inDate = this.defaultDate;
          }
        }
      }
    };
  </script>
  <style lang='scss' scoped>
   .hangs_two {
    width: 70%;
    color: chocolate;
    cursor: pointer;
    .text {
      text-decoration: underline;
      margin-right: 4px;
    }
    .iconfont {
      margin-right: 4px;
    }
  }
</style>